from typing import Optional, Type
from django import forms
from crispy_forms.helper import FormHelper
from django.utils.translation import gettext_lazy as _
from django.forms import modelformset_factory, widgets
from django.templatetags.static import static
from django.utils.html import format_html
from crispy_forms.layout import Submit

class CrispyFormMixin:
    submit_button_name = None
    
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.form_method = 'post'
        self.helper.form_error_title = _("错误")
        
        if self.submit_button_name:
            submit_btn = Submit('submit', self.submit_button_name)
            submit_btn.field_classes = 'tw:btn tw:btn-neutral'
            self.helper.add_input(submit_btn)
    

class CrispyModelForm(CrispyFormMixin, forms.ModelForm):
    pass

class CrispyForm(CrispyFormMixin, forms.Form):
    pass
            
class HiddenDeleteFormSet(forms.BaseModelFormSet):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for form in self.forms:
            # Hide DELETE field
            if 'DELETE' in form.fields:
                form.fields['DELETE'].widget = forms.HiddenInput()
        

    
def create_form(
    model_class,
    form_id: str,
    form_action: Optional[str],
    form_fields: list[str],
    form_method: str = 'post'
):
    class AuditForm(forms.ModelForm):
        class Meta:
            model = model_class
            fields = form_fields
            
        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)
            self.helper = FormHelper()
            self.helper.form_id = form_id
            self.helper.form_method = form_method
            if form_action:
                self.helper.form_action = form_action
            submit_btn = Submit('submit', _("提交"))
            submit_btn.field_classes = 'tw:btn'
            self.helper.add_input(submit_btn)
            
    return AuditForm

def create_readonly_modelformset(model_class, exclude_fields=None, form_class=None, **formset_kwargs):
    """
    Create a read-only ModelFormSet for a given model.
    
    Args:
        model_class: The Django model class
        exclude_fields: List of fields to exclude (optional)
        form_class: Base form class to inherit from (optional)
        **formset_kwargs: Additional arguments for modelformset_factory
    
    Returns:
        A read-only ModelFormSet class
    """
    if exclude_fields is None:
        exclude_fields = []

    # Use provided form_class or determine base form class from model fields
    BaseFormClass = form_class if form_class else forms.ModelForm
    class ReadOnlyModelForm(BaseFormClass):
        class Meta:
            model = model_class
            exclude = exclude_fields

        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)
            for field in self.fields.values():
                field.disabled = True

    # Set some default formset options that make sense for read-only formsets
    default_formset_kwargs = {
        'form': ReadOnlyModelForm,
        'extra': 0,
        'can_delete': False,
    }
    
    # Update with any additional kwargs provided
    default_formset_kwargs.update(formset_kwargs)

    return modelformset_factory(
        model_class,
        **default_formset_kwargs
    )

class WangEditorNextWidget(widgets.Input):
    @property
    def media(self):
        return forms.Media(
            css={
                "all": [
                    static("style/form.min.css")
                ]
            },
            js=[
                format_html(
                    '<script type="module" src="{}"></script>', 
                    static("script/components/wang-editor-next-autoload.js")
                )
            ]
        )

    def get_context(self, name, value, attrs):
        ctx = super().get_context(name, value, attrs)
        ctx['widget']['type'] = "hidden"
        ctx['widget']['attrs']['data-wangeditor'] = 'wangeditor'
        return ctx
    
class WangEditorNextField(forms.JSONField):
    widget = WangEditorNextWidget


class YesNoRadioSelect(forms.RadioSelect):
    def __init__(self, attrs=None):
        super().__init__(attrs, choices=[(True, _("是")), (False, _("否"))])


class YesNoField(forms.BooleanField):
    widget = YesNoRadioSelect
